package model

import (
	"content-sharing_0929/global"
	"gorm.io/gorm"
	"time"
)

type Sharing struct {
	Id        uint32         `gorm:"column:id;type:int UNSIGNED;comment:id;primaryKey;not null;" json:"id"`                                    // id
	UserId    int32          `gorm:"column:user_id;type:int;comment:用户ID;not null;" json:"user_id"`                                            // 用户ID
	ImageUrl  string         `gorm:"column:image_url;type:varchar(300);comment:图片;not null;" json:"image_url"`                                 // 图片
	Content   string         `gorm:"column:content;type:varchar(300);comment:文字内容;not null;" json:"content"`                                   // 文字内容
	Status    int8           `gorm:"column:status;type:tinyint(1);comment:状态: 0:审核中 1:公开 2:私密;not null;default:0;" json:"status"`              // 状态: 0:审核中 1:公开 2:私密
	LookNum   int32          `gorm:"column:look_num;type:int;comment:浏览量;not null;default:0;" json:"look_num"`                                 // 浏览量
	CreatedAt time.Time      `gorm:"column:created_at;type:datetime(3);comment:创建时间;not null;default:CURRENT_TIMESTAMP(3);" json:"created_at"` // 创建时间
	UpdatedAt time.Time      `gorm:"column:updated_at;type:datetime(3);not null;default:CURRENT_TIMESTAMP(3);" json:"updated_at"`
	DeletedAt gorm.DeletedAt `gorm:"column:deleted_at;type:datetime(3);default:NULL;" json:"deleted_at"`
}

func (s *Sharing) TableName() string {
	return "sharing"
}

// 添加
func (s *Sharing) AddSharing() error {
	return global.DB.Create(&s).Error
}

// 待审核
func (s *Sharing) FindSharingStatus() (list []Sharing, err error) {
	err = global.DB.Where("status = 0").Find(&list).Error
	return
}

// 审核
func (s *Sharing) UpdateSharing() error {
	return global.DB.Updates(&s).Error
}

// 查看公开
func (s *Sharing) FindSharing(page, pageSize int) (list []Sharing, err error) {
	err = global.DB.Where("status = 1").Scopes(Paginate(page, pageSize)).Find(&list).Error
	return
}

// 分页
func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {

		if page <= 0 {
			page = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}

// 查看用户
func (s *Sharing) FindSharingUserId() (list []Sharing, err error) {
	err = global.DB.Where("user_id =", s.UserId).Order("created_at look_num desc").Find(&list).Error
	return
}

// 查看
func (s *Sharing) FindSharingID() error {
	return global.DB.Where("id = ?", s.Id).Find(&s).Error
}

// 删除
func (s *Sharing) DeleteSharing() error {
	return global.DB.Delete(&s).Error
}
